We will start with a tiny program in which the slave processes do no work, and then expand its capabilities. Edit a file called p4simple.c and type:
This is one of the simplest p4 programs that you can write. Let's examine it. The #include "p4.h" statement must appear in all programs that use any p4 features. The procedure p4_initenv must be invoked before any other p4 procedures, and p4_wait_for_end must be invoked after all p4 processing is completed. The p4_get_my_id returns a unique integer id for each process, beginning with 0. The procedure p4_create_procgroup should only be invoked once (by process 0), and is responsible for creating all other processes. The way in which p4_create_procgroup determines how many other processes there should be, and where they should run, will be discussed shortly.
All processes that this program executes invoke the slave procedure, including process 0. Thus, in this program, the master process acts just like all other processes once it gets the environment established.
To understand how things get started, let's consider two separate situations. In the first situation, all processes are running on a single machine. Then, when process 0 starts, it executes the p4_create_procgroup procedure to start all other slaves. The other slaves are started on the same machine by means of a UNIX fork, and they immediately invoke a procedure named slave. Thus, these local slaves do not ever execute the main procdure.
In the second situation, there may be slaves running both on the same machine as process 0, and slaves running on other machines as well. In this situation, the first slave running on a remote machine will need to execute the main procedure. It will discover that it is not process 0. However, as part of initialization, process 0 will direct it to fork any additional slaves required on the same machine.
slave subroutine In some ways, the above example can be used a a prototype for all p4 programs, just by varying the content of the slave routine. The routine name slave is built into p4 in order to enable the same code to be run on shared-memory machines via fork or on remote machines via rsh. Different wrappers are automatically put around the slave code. These wrappers depend on the user code being called slave. Thus your p4 program must contain a subroutine called slave in order to link properly.
A More Complicated Example, ,A Minimal Example,Developing a Simple p4 Program